package com.lagou.rabbitmq.topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeoutException;

public class BeijingConsumer {

    public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        //指定协议 amqp://
        //指定用户名 root
        //指定密码 123456
        //指定host 47.115.74.219
        //指定端口号 5672
        //指定虚拟主机 %2f
        factory.setUri("amqp://root:123456@47.115.74.219:5672/%2f");

        Connection connection = factory.newConnection();

        Channel channel = connection.createChannel();

        //确保mq中有该队列，如果没有则创建
        String queueName = channel.queueDeclare().getQueue();

        //声明交换器
        //第一个参数 交换器名称
        //第二个参数 交换器类型
        //第三个参数 是否持久化
        //第四个参数 是否自动删除
        //第五个参数 交换器属性信息
        channel.exchangeDeclare("ex.topic", BuiltinExchangeType.TOPIC,true,false,null);

        channel.queueBind(queueName,"ex.topic","beijing.#");

        //监听消息，一旦有消息推送过来，就调用第一个lambda表达式
        channel.basicConsume(queueName,(consumer,message) -> {
            System.out.println(new String(message.getBody(), StandardCharsets.UTF_8));
        },(consumerTag) -> {});

    }

}
